package com.ruoyi.cqjd.filter;



import com.alibaba.fastjson2.JSON;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.cqjd.common.BaseContext;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.AntPathMatcher;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 用来检查是否有登录
 */
@WebFilter(filterName = "loginCheckFilter",urlPatterns = "/*")
@Slf4j
public class LoginCheckFilter implements Filter {

    //路径匹配器，支持通配符
    private final static AntPathMatcher PATH_MATCHER=new AntPathMatcher();

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request= (HttpServletRequest) servletRequest;
        HttpServletResponse response= (HttpServletResponse) servletResponse;

        //1、获取本次请求的URI
        String requestURI = request.getRequestURI();


//        如果请求url是下面之一，就放行
//        String[] urls={
//          "/employee/login",//url就是登录的url
//          "/employee/logout",//登出的url
//          "/backend/**",//backend的静态资源
//          "/front/**",//front的静态资源
//          "/common/**",
//                "/user/sendMsg",//移动端发送短信
//                "/user/login"//移动端登录
//        };

        //2、判断本次请求是否需要处理
//        boolean check = check(urls, requestURI);

        //3、如果不需要处理，则直接放行
//        if (check){
//            filterChain.doFilter(request,response);
//            return;
//        }

        //4、判断登录状态，如果已登录，直接放行
//        Long empId = (Long) request.getSession().getAttribute("employee");
//        if (empId !=null){
//
//            long id = Thread.currentThread().getId();
//            log.info("filter——线程id为："+id);
//
//            BaseContext.setCurrentId(empId);
//
//            filterChain.doFilter(request,response);
//            return;
//        }

        //4、判断移动端登录状态，如果已登录，直接放行
        Long userId = (Long) request.getSession().getAttribute("user");
        if (userId !=null){

            long id = Thread.currentThread().getId();
            log.info("filter——线程id为："+id);

            BaseContext.setCurrentId(userId);

            filterChain.doFilter(request,response);
            return;
        }

        //5、如果未登录，则返回未登录结果
        response.getWriter().write(JSON.toJSONString(R.fail("未登录")));
    }

    /**
     * 路径匹配，判断本次请求是否放行
     * @param urls
     * @param requestURI
     * @return
     */
//    private boolean check(String[] urls,String requestURI){
//        for (String url : urls) {
//            if (PATH_MATCHER.match(url,requestURI)){
//                return true;
//            }
//        }
//        return false;
//    }

}
